//
//  CMMyCenterListCtrl.m
//  CreditManger
//
//  Created by chaiyanan on 15/11/2.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "CMMyCenterListCtrl.h"
#import "LCCustomerActionSheet.h"
#import "CMGetUserInfoManager.h"
#import "CMLoginManager.h"
#import "UIImageView+WebCache.h"
#import "CMUploadImgInfo.h"
#import "CMUploadImgParam.h"
#import "CMUploadImgParser.h"

@interface CMMyCenterListCtrl ()
<
UINavigationControllerDelegate,
UIImagePickerControllerDelegate
>

@property (nonatomic, weak) IBOutlet UIImageView *headerIV;

@end

@implementation CMMyCenterListCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self requestToGetUserInfo];
    [self.headerIV setImageWithURL:[NSURL URLWithString:[CMLoginManager sharedCMLoginManager].currentUserInfo.headImg] placeholderImage:[UIImage imageNamed:@"头像-big"]];
    __weak typeof(self) weakSelf = self;
    [[NSNotificationCenter defaultCenter]addObserverForName:Notification_refreshUserInfo object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        [weakSelf requestToGetUserInfo];
    }];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.headerIV.layer.cornerRadius = 2.5f;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark - private method

- (void)requestToGetUserInfo
{
    __weak typeof(self) weakSelf = self;
    [CMGetUserInfoManager requestToGetUserInfoWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
        [weakSelf.headerIV setImageWithURL:[NSURL URLWithString:[CMLoginManager sharedCMLoginManager].currentUserInfo.headImg] placeholderImage:[UIImage imageNamed:@"头像-big"]];
    }];
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    headerView.backgroundColor = [UIColor clearColor];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //点的快回调用多次，怎么调整？？
    if (indexPath.section == 0 && indexPath.row == 0)
    {
        [[[LCCustomerActionSheet sharedLCCustomerActionSheet] initWithTitle:nil cancelButtonTitle:@"取消" cancelButtonAction:nil otherButtonTitles:@[@"拍照",@"相册选取"] otherButtonAction:^(NSInteger index,LCCustomerActionSheet *actionSheet)
          {
              if (index == 0)
              {
                  [self openImagePickerWithSourcheType:UIImagePickerControllerSourceTypeCamera];
                  
              }
              else
              {
                  [self openImagePickerWithSourcheType:UIImagePickerControllerSourceTypePhotoLibrary];
              }
              [actionSheet removeFromSuperview];
              
          }] showInView];
    }
}

#pragma mark -
#pragma mark - photo privateMethod
- (void)openImagePickerWithSourcheType:(UIImagePickerControllerSourceType)sourceType
{
    if (sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            [[[UIAlertView alloc]initWithTitle:@"提示" message:@"该设备不支持相机" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
            return;
        }
    }
    
    CMAppDelegate.isFromCamera = YES;
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    picker.sourceType = sourceType;
    picker.delegate = self;
    picker.allowsEditing = YES;
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark -
#pragma mark - imagePickerDelegate

- ( void )imagePickerController:( UIImagePickerController *)picker didFinishPickingMediaWithInfo:( NSDictionary *)info
{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
    self.headerIV.image = image;
    [self requestToUploadImgWithImageData:UIImageJPEGRepresentation(image, 0.5)];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


- ( void )imagePickerControllerDidCancel:( UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -
#pragma mark - net method

- (void)requestToUploadImgWithImageData:(NSData *)imageData;
{
    CMUploadImgParam *param = [[CMUploadImgParam alloc]init];
    param.uid = [CMLoginManager sharedCMLoginManager].currentUserInfo.uid;
    param.token = [CMLoginManager sharedCMLoginManager].currentUserInfo.token;
    param.file = imageData;
    
    CMUploadImgParser *parser = [[CMUploadImgParser alloc]init];
    [NetCenter postDataFromURL:Method_uploadImg params:param parser:parser result:^(ParserResult *myResult) {
        CMUploadImgInfo *info = (CMUploadImgInfo *)myResult.result;
        [CMLoginManager sharedCMLoginManager].currentUserInfo.headImg = info.headImg;
        [CMLoginManager cacheCurrentUserToUserDefault:[CMLoginManager sharedCMLoginManager].currentUserInfo];
    } failure:^(NSError *error) {
        
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
